import { defineStore } from 'pinia';
import { ref } from 'vue';
import { io } from 'socket.io-client';

export const useSocketStore = defineStore('socket', () => {
  const socket = ref(null);
  const isConnected = ref(false);
  const messages = ref([]);
  let reconnectTimer = null;

  const connect = () => {
    if (socket.value && isConnected.value) {
      console.log('Socket.IO is already connected.');
      return;
    }
    
    // 从配置文件或环境变量中获取URL
    const config = window.appConfig || {};
    const socketURL = config.VITE_SOCKET_IO_URL || 'http://localhost:5101';
    
    // 注意：socket.io-client 使用 http/https URL
    const newSocket = io(socketURL, {
        reconnection: true,
        reconnectionAttempts: Infinity,
        reconnectionDelay: 1000,
        reconnectionDelayMax: 5000,
        randomizationFactor: 0.5
    });

    newSocket.on('connect', () => {
      console.log('Socket.IO connected successfully with ID:', newSocket.id);
      isConnected.value = true;
      socket.value = newSocket;
    });

    // 通用消息监听器
    newSocket.onAny((eventName, ...args) => {
        console.log(`Received event "${eventName}":`, args);
        messages.value.push({ eventName, data: args });
    });

    newSocket.on('disconnect', (reason) => {
      console.log('Socket.IO disconnected:', reason);
      isConnected.value = false;
      socket.value = null;
    });

    newSocket.on('connect_error', (error) => {
      console.error('Socket.IO connection error:', error);
    });
  };

  const sendMessage = (eventName, data) => {
    if (socket.value && isConnected.value) {
        socket.value.emit(eventName, data);
    } else {
      console.error('Socket.IO is not connected.');
    }
  };

  const disconnect = () => {
    if (socket.value) {
      socket.value.disconnect();
    }
  };
  
  // 清空消息记录
  const clearMessages = () => {
    messages.value = [];
  };

  return {
    socket,
    isConnected,
    messages,
    connect,
    disconnect,
    sendMessage,
    clearMessages
  };
});
